<template>
  <div class="comment-container">

    <div v-if="uid != ''">
      <div class="comment-nav">
        <div class="comment-nav-left">
          <span style="font-size: 20px; font-weight: bold; color: black;">评论</span>
          <span style="padding: 0 0 0 5px;">863</span>
        </div>

        <div class="comment-nav-right">
          <span :style="{ color: (replyAreaSort ? '#9499A0' : 'black'), cursor: 'pointer' }"
            @click="replySortByHigh">最热</span>
          <span style="border-left: 1px solid;"></span>
          <span :style="{ color: (replyAreaSort ? 'black' : '#9499A0'), cursor: 'pointer' }"
            @click="replySortByTime">最新</span>
        </div>

      </div>

      <!-- 当前账号发表留言 -->
      <div class="reply-box">
        <div class="reply-box-main">
          <!-- 头像部分 -->
          <div class="reply-box-avatar">
            <div class="avatar-details">
              <!-- <img src="../../../public/img/default.jpg" alt="" /> -->
              <img :src="userAvatar" alt="" />
            </div>
          </div>

          <div style="width: 90%;">
            <a-textarea v-model:value="yourComment" placeholder="精彩评论等你来发布" auto-size style="line-height: 40px;"
              @focus="publishFocus" @blur="publishBlur" />
          </div>
        </div>


        <div class="publish-comment" ref="publishComment">
          <span></span>
          <a-button style="margin-left: auto;" @click="commitComment" v-noReClick>发布</a-button>
        </div>
      </div>


      <div class="root-comment" v-for=" (item, index) in commentList" :key="index">
        <!-- 头像部分 -->
        <div class="root-avatar" @click="enterUserInfo(item.userId)">
          <div class="avatar-details">
            <!-- <img src="../../../public/img/default.jpg" alt="" /> -->
            <img :src="item.avatar" alt="" />
          </div>
        </div>

        <!-- 留言部分 -->
        <div>
          <!-- 用户名 -->
          <div style="display: flex; align-items: center;height: 30px;" @click="enterUserInfo(item.userId)">
            <span>{{ item.userName }}</span>
          </div>
          <!-- 留言部分 -->
          <div style="font-size: 15px;line-height: 24px;">
            <span>
              {{ item.content }}
              <!-- 看完donk那条，单纯觉得不配排top3，牛就牛在摸烟比较大胆吧，后续队友道具真的太好了，还有大狙开始的过路费。但是对阿汤哥的状态有了新的认知，真的太差了。蛇死了之后，还在切道具扔，还空了一枪。（反复回放了好几遍，他开枪了donk才刚刚进烟）这A队真的是四菜，把staehr拖累麻了。 -->
            </span>

            <div class="reply-action">
              <span>{{ formatByPattern(item.sendTime, 'YYYY-MM-DD HH:mm') }}</span>
              <span :class="{'action': true,'action-active': item.userAgree}" @click="like($event, item)">
                <LikeFilled /> {{ item.agree }}
              </span>
              <span :class="{'action': true,'action-active': item.userDisagree}" @click="unLike($event, item)">
                <DislikeFilled />
              </span>
              <!-- 回复楼主 -->
              <span class="action" @click="reply($event, item, index)">回复</span>
            </div>
          </div>
        </div>

        <div v-if="item.replyNum > 0 && !(item.showReply)" :id="'showReply' + index">
          <span>共计{{ item.replyNum }} 条评论, </span> <span class="action" @click="showReply(item, index)">点击展开</span>
        </div>

        <div :id="'subReply' + index" style="display :none;">
          <div v-for="(subItem, subIndex) in item.reply" :key="subIndex" class="sub-reply">
            <div class="root-avatar" @click="enterUserInfo(subItem.userId)">
              <div class="sub-avatar-details">
                <!-- <img src="../../../public/img/default.jpg" alt="" /> -->
                <img :src="subItem.avatar" alt="" />

              </div>
            </div>

            <!-- 留言部分 -->
            <div>
              <!-- 用户名 -->
              <div style="display: flex; align-items: center;height: 30px;" @click="enterUserInfo(subItem.userId)">
                <span>{{ subItem.userName }}</span>
              </div>
              <!-- 留言部分 -->
              <div style="line-height: 24px;">
                <span v-if="subItem.replyUserId && (subItem.replyUserId != item.userId)">回复 @
                  <span style="color: #2bb3eb; cursor: pointer;">{{ subItem.replyUserName }}</span> : 
                </span>
                <span>
                  {{ subItem.content }}
                  <!-- 看完donk那条，单纯觉得不配排top3，牛就牛在摸烟比较大胆吧，后续队友道具真的太好了，还有大狙开始的过路费。但是对阿汤哥的状态有了新的认知，真的太差了。蛇死了之后，还在切道具扔，还空了一枪。（反复回放了好几遍，他开枪了donk才刚刚进烟）这A队真的是四菜，把staehr拖累麻了。 -->
                </span>

                <div class="reply-action">
                  <span>{{ formatByPattern(subItem.sendTime, 'YYYY-MM-DD HH:mm') }}</span>
                  <span :class="{'action': true,'action-active': subItem.userAgree}" @click="like($event, subItem)">
                    <LikeFilled /> {{ subItem.agree }}
                  </span>
                  <span :class="{'action': true,'action-active': subItem.userDisagree}" @click="unLike($event, subItem)">
                    <DislikeFilled />
                  </span>
                  <!-- 回复楼层中某人的评论 -->
                  <span class="action" @click="reply($event, subItem, index)">回复</span>
                </div>
              </div>
            </div>
          </div>

          <a-pagination v-model:current="item.page.current" v-model:page-size="item.page.pageSize" 
          @change="subPageChange(item.page.current,item.page.pageSize,item)" size="small"
          :show-total="total => `一共 ${total} 条评论`"
          :total="item.page.total" show-less-items />
        </div>



        <!-- 当前账号回复评论 -->
        <div :id="index" style="display: none;">
          <div class="reply-box">
            <div class="reply-box-main">
              <!-- 头像部分 -->
              <div class="reply-box-avatar">
                <div class="avatar-details">
                  <img :src="userAvatar" alt="" />
                  <!-- <img src="../../../public/img/default.jpg" alt="" /> -->
                </div>
              </div>

              <div style="width: 90%;">
                <a-textarea v-model:value="yourReply" :placeholder="placeholderText" auto-size style="line-height: 40px;"
                  @focus="replyFocus((index + '-1'))" @blur="replyBlur((index + '-1'), index)" :id="index + '-2'" />
              </div>
            </div>

            <!-- class="publish-comment" -->
            <div class="publish-comment" :id="index + '-1'">
              <span></span>
              <a-button style="margin-left: auto;" @click="commitReply(item , index)" v-noReClick>发布</a-button>
            </div>
          </div>
        </div>


        <div style="margin: 4px 0 0 0; border-bottom: 1px #d6cfcf solid;"></div>
      </div>

      <div style="display: flex; justify-content: center;padding: 10px 0 0 0;">
        到底了,没有更多了
      </div>
    </div>

    <div v-else>
      <div class="not-login-comment">
        <div class="not-login-text">
          <LockOutlined /> <span>登陆查看精彩评论</span>
        </div>
      </div>
    </div>

  </div>
</template>
<script setup>
import { ref, reactive, defineProps, computed, onMounted, onUnmounted } from 'vue'
import { DislikeFilled, LikeFilled, LockOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { useStore } from 'vuex';
import { debounce } from '@/utils/debounce';
import { sendComment, getCommentList, getSubCommentList ,agree , disagree } from '@/api/chatRecord'
import { formatByPattern } from '@/utils/dateFormat';
import {useRouter} from 'vue-router'
onMounted(() => {

  window.addEventListener('scroll', scrollListener);

})

const router = useRouter();
const placeholderText = ref('');

let commentList = ref([])
const props = defineProps({
  videoId: {
    type: String,
    default: null,
    required: true
  }
})

let replyObj = null;

const store = useStore();

let uid = computed(() => {
  var userId = store.getters['user/userId'];

  if (userId && userId != '') {

    //localStorage中数据变化时 对应设置的页面缓存数据改变
    initComment({
      start: 0,
      end: 20,
      videoId: props.videoId,
      sortField: 'sortRank',
      flag: true
    });

    localMap = {};
  }
  return  userId;
})

let userAvatar = computed(() => {
  var avatar = process.env.VUE_APP_VIDEO_PROXY_TARGET + '/image/' + store.getters['user/avatar'];
  return avatar;
})

const replyAreaSort = ref(false); // 评论区按哪种方式呈现 false 最热 true 最新

let yourComment = ref(''); //发表评论
let yourReply = ref(''); //回复他人言论

const publishComment = ref(''); //发布按钮所在区域绑定的ref

let timer = null; //发送评论按钮消失定时器

const data = {
  start: 0,
  end: 20,
  videoId: props.videoId,
  sortField: 'sortRank'
}

/**
 * 监控页面滚动函数
 */
const scrollListener = () => {

  //没有登陆时 直接返回 不向后端发送请求
  if (uid.value == ''){
    return ;
  }

  var windowHeight = document.body.clientHeight || document.documentElement.clientHeight;

  var elementHeight = document.body.scrollHeight || document.documentElement.scrollHeight;
  var scrollHeight = document.body.scrollTop || document.documentElement.scrollTop;

  if (windowHeight + scrollHeight + 2 > elementHeight) {
    console.log('到底了');
    debounceFunc.apply(null, []);
  }

}

/**
 * 初始化获取评论列表数据
 * @param {Obj} msg 
 */
const initComment = (msg) => {

  var sendMsg = data;

  if (msg) {
    sendMsg = msg;
  }

  getCommentList(sendMsg).then((res) => {

    if (typeof res.data[0].chatId === 'undefined') {
      window.removeEventListener('scroll', scrollListener);
      return ;
    }

    res.data.map(item => {
      item['reply'] = [];
      item['page'] = getSubByChatId(item.chatId);

      item.avatar = process.env.VUE_APP_VIDEO_PROXY_TARGET + '/image/' + item.avatar;
    });
    // commentList.value.push(...res.data);
    if(msg.flag){
      commentList.value = res.data
    }else{
      commentList.value.push(...res.data);
    }
    

  })
}

const enterUserInfo = (userId) => {
  router
}

/**
 * 瀑布流式更新显示评论区数据
 */
const debounceFunc = debounce(() => {
  data.start = data.end;
  data.end = data.end + 20;
  getCommentList(data).then((res) => {

    if (typeof res.data[0].chatId === 'undefined') {
      window.removeEventListener('scroll', scrollListener);
    } else {
      res.data.map(item => {
        item['reply'] = [];
        item['page'] = getSubByChatId(item.chatId);
        item.avatar = process.env.VUE_APP_VIDEO_PROXY_TARGET + '/image/' + item.avatar;
      });
      commentList.value.push(...res.data);
    }
  })
  .catch(err => {
    window.removeEventListener('scroll', scrollListener);
  })


}, 500);


/**
 * 赞同某条评论
 * @param {Event} e 
 * @param {Object} item 
 */
const like = (e, item) => {

  const msg = {chatId: item.chatId, num: 0};

  item.userAgree = !item.userAgree;
  item.userDisagree = false;

  msg.num = item.userAgree ? 1 : -1;

  item.agree = item.userAgree ? item.agree + 1 : item.agree - 1;

  agree(msg).then(res => {})

}

/**
 * 不赞同某条评论
 * @param {Event} e 
 * @param {Object} item 
 */
const unLike = (e, item) => {

  const msg = {chatId: item.chatId, num: 0};

  item.userDisagree = !item.userDisagree;
  item.userAgree = false;

  msg.num = item.userDisagree ? -1 : 1;

  disagree(msg).then(res => {})

}
/**
 * 回复楼层中某人的评论 排除回复楼主
 * @param {Event} e 
 * @param {Object} obj 
 * @param {String} index //回复框展示位置所处的item的dom元素的id
 */
const reply = (e, obj, index) => {

  replyObj = obj;

  placeholderText.value = `回复@${obj.userName}`;

  document.getElementById(index).style.display = 'block';
  document.getElementById(index + '-2').focus();
}


/**
 * 按时间排序评论
 */
const replySortByTime = () => {
  replyAreaSort.value = !replyAreaSort.value;

  initComment({
      start: 0,
      end: 20,
      videoId: props.videoId,
      sortField: 'sendTime',
      flag: true
    });
}

/**
 * 按评论热度排序评论
 */
const replySortByHigh = () => {
  replyAreaSort.value = !replyAreaSort.value;
  initComment({
      start: 0,
      end: 20,
      videoId: props.videoId,
      sortField: 'sortRank',
      flag: true
    });
}

/**
 * 聚焦发表评论输入框时 显示发送评论按钮
 */
const publishFocus = () => {
  if (!publishComment.value.classList.contains('publish-comment-show')) {
    publishComment.value.classList.add('publish-comment-show')
  }
}

/**
 * 失焦发表评论输入框时 使用定时器隐藏评论按钮
 * 
 */
const publishBlur = () => {

  timer = setTimeout(() => {
    publishComment.value.classList.remove('publish-comment-show')
  }, 1000)
}

/**
 * 聚焦发表评论输入框时 显示发送评论按钮
 * @param {String} id 显示按钮的dom元素的id 
 */
const replyFocus = (id) => {
  if (!document.getElementById(id).classList.contains('publish-comment-show')) {
    document.getElementById(id).classList.add('publish-comment-show');
  }
}

/**
 * 失焦发表评论输入框时 使用定时器隐藏评论按钮
 * 
 */
const replyBlur = (index, parentId) => {

  timer = setTimeout(() => {
    document.getElementById(index).classList.remove('publish-comment-show');
    document.getElementById(parentId).style.display = 'none';
  }, 1000)
}



/**
 * 提交评论到后台
 */
const commitComment = () => {

  if (timer) {
    clearTimeout(timer);
  }

  if (yourComment.value == '') {
    return message.info({
      content: '尚未输入内容',
      duration: 1.5
    })
  }

  const msg = {
    videoId: props.videoId,
    parentId: '0',
    userId: uid.value,
    userName: store.getters['user/userName'],
    content: yourComment.value,
    contentType: false,
    agree: 0,
    disagree: 0,
    replyNum: 0,
    showReply: false,
  }

  sendComment(msg).then((res) => {
    message.success({
      content: '评论成功',
      duration: 2
    })
    msg['chatId'] = res.data;
    msg['page'] = getSubByChatId(msg.chatId);
    msg['avatar'] = process.env.VUE_APP_VIDEO_PROXY_TARGET + '/image/' + store.getters['user/avatar'];

    commentList.value.unshift(msg);

    //输入框清空内容
    yourComment.value = '';

    //评论框1s后消失
    publishBlur();
  })
}

/**
 * 回复他人评论到后台
 * @param {Object} chatObj
 * @param {Number} index
 */
const commitReply = (chatObj , index) => {

  if (timer) {
    clearTimeout(timer);
  }

  if (yourReply.value == '') {
    return message.info({
      content: '尚未输入内容',
      duration: 1.5
    })
  }

  var temp = {};
  //回复楼层中评论
  if (replyObj && replyObj.parentId != '0') {
    temp = replyObj;
  } else if (replyObj && replyObj.parentId == '0') {//回复楼主
    temp = chatObj;
  }
  var msg = {
    videoId: props.videoId,
    parentId: chatObj.chatId,
    userId: uid.value,
    userName: store.getters['user/userName'],
    content: yourReply.value,
    contentType: false,
    agree: 0,
    disagree: 0,
    replyUserId: temp.userId,
    replyUserName: temp.userName,
  };

  sendComment(msg).then((res) => {
    message.success({
      content: '评论成功',
      duration: 2
    })
    msg['chatId'] = res.data;
    msg['avatar'] = userAvatar.value;

    if (typeof replyObj === 'number') {
      chatObj.reply[replyObj].unshift(msg);
    }
    else if (typeof replyObj === 'object') {
      chatObj.reply.unshift(msg);
    }

    //清空回复框内容
    yourReply.value = '';
    //使回复框消失
    replyBlur(`${index}-1`,index);
  })
}

/**
 * 展开某一楼层的评论
 * @param {Object} item 
 * @param {Number} index 
 */
const showReply = (item, index) => {

  item['showReply'] = true;

  var msg = getSubByChatId(item.chatId);

  getSubCommentList(msg).then((res) => {

    res.data.list.map(item => {
      item.avatar = process.env.VUE_APP_VIDEO_PROXY_TARGET + '/image/' + item.avatar;
    });
    item.reply.push(...res.data.list);

    item.page.total = res.data.total;

    document.getElementById(`subReply${index}`).style.display = 'block';
  })

}


/**
 * 构建本页面的基本缓存
 * @param {String} chatId
 */
let localMap = {};
const getSubByChatId = (chatId) => {
  if (localMap[chatId]) {
    var temp = localMap[chatId];
    temp.start = temp.end;
    temp.end += 5;
    return temp;
  }

  localMap[chatId] = {
    start: -5,
    end: 0,
    videoId: props.videoId,
    parentId: chatId,
    sortField: 'sortRank',
    current: 1,
    total: 0,
    pageSize: 5,
  }

  return localMap[chatId];
}

/**
 * 
 * @param {Number} current 
 * @param {Number} pageSize 
 * @param {Object} item 
 */
const subPageChange = (current,pageSize,item) => {
  console.log(current,pageSize,item);
}

onUnmounted(() => {
  window.removeEventListener('scroll', scrollListener);
})
</script>
<style scoped>
.comment-container {
  position: relative;
}

.not-login-comment {
  width: 100%;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.not-login-text {
  font-size: 20px;
  display: flex;
  align-items: center;
}

.comment-nav {
  margin: 10px 0 0 10px;
  display: flex;
  align-items: center;
  color: #9499A0;
}

.comment-nav-left {
  display: flex;
  align-items: center;
  width: 20%;
}

.comment-nav-right {
  display: flex;
  justify-content: space-around;
  width: 15%;
}

.reply-box {
  padding: 10px 0 10px 0;
  position: relative;
}

.reply-box-main {
  display: flex;
  align-items: center;
}

.reply-box-avatar {
  width: 80px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.publish-comment {
  display: flex;
  padding: 10px 0 0 0;
  height: 0;
  transition: height 0.5s ease;
  overflow: hidden;
}

.publish-comment-show {
  height: 50px;
}

.root-comment {
  padding: 22px 0 0 80px;
}

.avatar-details {
  width: 50px;
  height: 50px;
  border-radius: 25px;
  background: white;
  color: skyblue;
  font-size: 15px;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

.root-avatar {
  position: absolute;
  left: 0;
  width: 80px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.reply-action {
  display: flex;
  width: 40%;
  font-size: 13px;
  justify-content: space-between;
  align-items: center;
  color: #9499A0;
}

.action {
  cursor: pointer;

}

.action:hover {
  color: #2bb3eb;
}

.action-active {
  color: #2bb3eb;
}

.sub-reply {
  position: relative;
  padding: 22px 0 0 80px;
}

.sub-avatar-details {
  width: 40px;
  height: 40px;
  border-radius: 20px;
  background: white;
  color: skyblue;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}
</style>